package com.netcracker.ui.command;

import com.netcracker.entity.Book;
import com.netcracker.entity.Right;
import com.netcracker.util.service.BookService;
import com.netcracker.util.service.ServiceFacade;
import com.netcracker.util.service.exception.DataTransmittingException;
import com.netcracker.util.service.exception.NullDataException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.LoggerFactory;

public class DeleteBookCommand implements Command {
    private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(DeleteBookCommand.class);
    private final ServiceFacade serviceFacade;

    public DeleteBookCommand(ServiceFacade serviceFacade) {
        this.serviceFacade = serviceFacade;
    }

    @Override
    public String execute(HttpServletRequest request, HttpServletResponse response) {
        Integer bookID = Integer.parseInt(request.getParameter("bookID"));
       
        BookService bookService = serviceFacade.getBookService();
        try {
            Book book = bookService.readBook(bookID);
            Right right = (Right) request.getSession().getAttribute("right");
            String bookLogin = book.getUser().getLogin();
            String currentLogin = (String) request.getSession().getAttribute("user");
            if (bookLogin.equals(currentLogin) || (right != null && right.equals(Right.ADMIN))) {
               bookService.deleteBook(bookID);
               request.setAttribute("success", "Книга удалена.");
               LOGGER.info("Book was deleted: ", bookID);    
               return "?action=findBook&type=byUser&id="+request.getSession().getAttribute("id");  
            } else {
                request.setAttribute("error", "Недостаточно прав на удаление книги.");
                return "index.jsp";
            }
        } catch (NullDataException ex) {
            request.setAttribute("error", "Книга не найдена.");
            return "index.jsp";
        } catch (DataTransmittingException ex) {
            request.setAttribute("error", "Ошибка обращения к БД.");
            LOGGER.error("DB error: ", ex);
            return "index.jsp";
        } 
    }
}
